#!/bin/bash
# 当前用户具有sudo 权限,且当前系统为Centos7.x，如果主机9100端口被占用会调整为9800
set -e
set -u

function init(){
tar xvfz /tmp/node_exporter-0.18.1.linux-amd64.tar.gz -C $HOME
echo "init end,the file /tmp/node_exporter-0.18.1.linux-amd64.tar.gz is not exist"
main
}

function main(){
echo "main start"
# 检查node_exporter 进程是否存在，存在需要先kill 掉
check_node_exporter_status

if [[ -d $HOME/node_exporter-0.18.1.linux-amd64/  ]];then
  sudo cp $HOME/node_exporter-0.18.1.linux-amd64/node_exporter /usr/sbin/node_exporter
else
  echo "请检查当前用户 $USER 所在家目录是否已安装node_exporter,没有请在主机监控界面点击安装并启动进行安装"
  exit 1
fi

init_node_exporter_systemd
echo "main end"
}

# 检查 node_exporter 进程是否存在，存在则直接kill 掉
function check_node_exporter_status(){
echo "check node exporter status start "
# 取消服务屏蔽
sudo systemctl unmask node_exporter
node_exporer_proc=$(ps -ef|grep node_exporter|grep -v grep|grep -v $$|awk '{print $2}')

if [[ $node_exporer_proc != "" ]]; then
echo "node_exporter process id is $node_exporer_proc"
sudo kill  $node_exporer_proc
fi
echo "check node exporter status end "
}

# node_exporter 加入 systemd
function init_node_exporter_systemd(){
sudo touch /usr/lib/systemd/system/node_exporter.service 
sudo chmod o+w /usr/lib/systemd/system/node_exporter.service 
sudo chmod a+x /usr/sbin/node_exporter
sudo mkdir -p /var/lib/node_exporter/textfile_collector
sudo chown $USER /var/lib/node_exporter/textfile_collector

check_port_is_occupied

sudo systemctl daemon-reload
sudo systemctl enable node_exporter
sudo systemctl start node_exporter
echo "sudo systemctl is-enabled node_exporter result ===> $(sudo systemctl is-enabled node_exporter)"
echo "sudo systemctl status node_exporter"
}

# the port of node_exporter is 9100,if occupied will be adjusted  to 9800
function check_port_is_occupied(){
if sudo netstat -anp|grep :9100  > /dev/null ; then
sudo cat << EOF > /usr/lib/systemd/system/node_exporter.service 
[Service]
Type=simple
User=$USER
ExecStart=/usr/sbin/node_exporter --web.listen-address=:9800 --collector.processes  --collector.systemd --collector.textfile.directory /var/lib/node_exporter/textfile_collector
Restart=on-failure

[Install]
WantedBy=multi-user.target

[Unit]
Description=node_exporter service daemon
After=network.target 
EOF
else
sudo cat << EOF > /usr/lib/systemd/system/node_exporter.service 
[Service]
Type=simple
User=$USER
ExecStart=/usr/sbin/node_exporter --collector.processes --web.listen-address=:9100 --collector.systemd --collector.textfile.directory /var/lib/node_exporter/textfile_collector
Restart=on-failure

[Install]
WantedBy=multi-user.target

[Unit]
Description=node_exporter service daemon
After=network.target 
EOF
fi	
}

init